﻿using System;
using System.Linq;
using System.Reflection;
using Fuse8.DomainFramework.Common;

namespace Fuse8.ContentManagementFramework.SystemFacade.Utilities
{
    public static class MapEntityFromProperties
    {
        public static void SetProperty(object source, string propertyName, object propertyValue)
        {
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotEmpty(propertyName, "propertyName");
            Guard.ArgumentNotNull(propertyValue, "propertyValue");

            PropertyInfo propertyInfo = source.GetType().GetProperty(propertyName);
            if (propertyInfo != null)
            {
                //TO DO: add more available types
                if (propertyInfo.PropertyType == typeof(int))
                {
                    propertyInfo.SetValue(source, int.Parse(propertyValue.ToString()), null);
                }
                else if (propertyInfo.PropertyType == typeof(int?))
                {
                    if ((propertyValue != null) && !string.IsNullOrWhiteSpace(propertyValue.ToString()))
                    {
                        propertyInfo.SetValue(source, int.Parse(propertyValue.ToString()), null);
                    }
                }
                else if (propertyInfo.PropertyType == typeof(bool))
                {
                    // standard Html.CheckBox or Html.CheckboxFor renders <input type="checkbox" value="true" /> and <input type="hidden" value="False" /> so if checkbox is checked there are two values in form
                    string[] values = propertyValue.ToString().Split(',');
                    string value;
                    if (values.Any(p => p.Equals("true", StringComparison.OrdinalIgnoreCase)))
                    {
                        value = "true";
                    }
                    else
                    {
                        value = propertyValue.ToString();
                    }
                    propertyInfo.SetValue(source, bool.Parse(value), null);
                }
                else
                {
                    propertyInfo.SetValue(source, propertyValue, null);
                }
            }
        }
    }
}
